import { Popup } from 'devextreme-react';
import React, { useImperativeHandle, useRef, useState } from 'react';
import { intl } from '../../../utils';

const PopupComponents = React.forwardRef((props: any, ref: any) => {
  const [visible, setVisible] = useState<boolean>(false);
  const popupRef = useRef<any>(null);
  const diaParams = useRef<any>();

  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: (params: any) => {
      diaParams.current = params;
      if (params.width) {
        props = { ...props, width: params.width, height: params.height };
        debugger;
      }

      setVisible(true);
    },
    closeDia: () => {
      setVisible(false);
    },
    getInstance: () => {
      return popupRef.current.instance();
    },

    clearCon: () => {
      // debugger;
      return popupRef.current.instance().dispose();
    },
  }));

  const onOk = () => {
    if (diaParams.current?.okCallback) {
      diaParams.current?.okCallback();
    }
    setVisible(false);
  };

  const onCancel = () => {
    if (diaParams.current?.cancelCallback) {
      diaParams.current?.cancelCallback();
    }
    setVisible(false);
  };

  const onClose = () => {
    if (diaParams.current?.onClose) {
      diaParams.current?.onClose();
    }
    setVisible(false);
  };

  return (
    <>
      <Popup
        ref={popupRef}
        visible={visible}
        title={diaParams.current?.title}
        width={props?.width ? props?.width : 500}
        height={props?.height ? props?.height : 150}
        // {...props}
        onContentReady={(e: any) => {
          debugger;
          console.log('li,eee', e);
        }}
        // dragOutsideBoundary={true}
        resizeEnabled={true}
        onHiding={() => onClose()} // x的关闭
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',

            options: {
              type: '',
              text: diaParams.current?.cancelText || intl('pub.cancel', '否'),
              onClick: () => {
                onCancel();
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: diaParams.current?.okText || intl('pub.ok', '是'),
              type: 'default',
              onClick: () => onOk(),
            },
          },
        ]}
        contentRender={diaParams.current?.content}
      />
    </>
  );
});

export default PopupComponents;
